package week12.consumer;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class JMSConsumer {

    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;

    public static void main(String[] args) {
        // 连接工厂，用来生产Connection
        ConnectionFactory connectionFactory;
        // 连接
        Connection connection = null;
        // 会话，接收或者发送消息的线程
        Session session;
        // 消息的目的地
        Destination queueDestination;
        //消费者
        MessageConsumer consumer;
        try {
            // 实例化连接工厂
            connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKEURL);
            // 通过连接工厂获取连接
            connection = connectionFactory.createConnection();
            // 启动连接
            connection.start();
            // 获取Session
            session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 创建消息队列，queue
            queueDestination = session.createQueue("week12.topic09");

             consumer = session.createConsumer(queueDestination);

            while (true){
                //消费方式是死等receive()
                TextMessage textMessage = (TextMessage) consumer.receive();
                if(null != textMessage){
                    System.out.println("消费者接受到消息："+textMessage.getText());
                }else {
                    break;
                }
            }
        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            if(connection != null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }           
        }
    }



}
